import Qs from 'qs'
import axios from 'axios'
import { baseURL } from './config.js'
import {getCookie, getStore} from '../commonUtil/mUtils'
let token = '';
function fetch(url, data) {
  let token=getCookie('token')!='undefined'?getCookie('token'):'';
  // let randomNum = md5(getStore('randomNum')); // 获取随机数
  // console.log(randomNum);
  return new Promise((resolve, reject) => {
    //创建axios实例，把基本的配置放进去
    const instance = axios.create({
      headers: {
        "Content-Type": " application/json;charset=utf-8",
        // "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
        'token': token
      },
      dataType: "json",
      // method: 'post',
      method:'get',
      mode: 'cors',
      xhrFields: {withCredentials: true},
      // timeout:1000,
      baseURL: baseURL,
      url: url,
      //参数转成键值对形式；
      transformRequest: [function (data) {
        // let timeStamp = (Date.parse(new Date()) / 1000) + '';
        // let res;
        // if (data) {
        //   res = Qs.stringify(data) + '&token=' + token + '&timestamp=' + timeStamp + '&url=' + url + '&nonce=' + randomNum;
        // } else {
        //   res = 'token=' + token + '&timestamp=' + timeStamp + '&url=' + url + '&nonce=' + randomNum;
        // }
        // // console.log(res);
        // res = res.split('&').sort().join('&') + 'XjdA0kdjd51kDV3A9dw2A';
        // res = md5(res);
        // // 把md5的数据传给后端
        // data = Qs.stringify(data) + '&token=' + token + '&timestamp=' + timeStamp + '&sign=' + res + '&nonce=' + randomNum;

        // data = Qs.stringify(data)+'&token='+token;  //123456
        data = Qs.stringify(data);  //123456
        return data;
      }],
      params:data,//与请求一起发送的URL参数,必须是纯对象或URLSearchParams对象
      // data: data,//`data`是要作为请求主体发送的数据
    });
    //请求成功;
    instance(url, data).then(res => {
      // console.log(res)
      resolve(res)
      //请求失败；
    }).catch(err => {
      // console.log(err);
      if (err && err.response.status == 500) {
        alert('接口500...')
      }
      reject(err)
    });
    //  响应拦截器；
    instance.interceptors.request.use(response => {
      // 对响应数据做点什么
      // console.log(response)
      return response
    }, error => {
      // 对响应错误做点什么
      console.log(error)
      return Promise.reject(error)
    })
  })
}

export default fetch
